package com.jeehentor.common.exception;

import com.jeehentor.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description : 全局异常捕获
 * @Author : wzd
 * @Date : 2024/4/7 17:15
 * @Version : 1.0
 **/

@Slf4j
//只要类的注解上有这些注解。那么发生的异常都能被捕获到
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
public class GlobalExceptionHandler {

    /**
     * 将业务层抛出的异常信息捕获到，然后交给全局异常处理器去处理，给前端提供错误信息
     * @param exception
     * @return
     */
    @ExceptionHandler(HentorException.class)
    public Result<String> exceptionCategoryDelete(HentorException exception){
        log.info(exception.getMessage());
        return Result.error(exception.getMessage());

    }

    /**
     * AccessDeniedHandler会被全局异常处理器捕获到
     * 全局异常处理器捕获到异常之后，会调用该方法
     * 返回一个Result对象，给前端提供错误信息
     * @param ex
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    public Result<String> handleAccessDeniedException(Exception ex) {
        Result<String> result = new Result<>();
        result.setCode(HttpStatus.FORBIDDEN.value());
        result.setMessage("无权限访问");
        return result;
    }
    /**
     * 处理除0异常捕获
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result<String> exceptionHandler(Exception exception){
        //在控制台打印错误信息
        log.error("系统异常：",exception);
        return Result.error("系统异常："+exception.getMessage());
    }


}

